const { User } = require('./model');
const { Op } = require('sequelize');

class UserDao {
  // 创建用户
  async createUser(userData) {
    try {
      return await User.create(userData);
    } catch (error) {
      throw new Error(`创建用户失败: ${error.message}`);
    }
  }

  // 根据用户名查找用户
  async findByUsername(username) {
    try {
      return await User.findOne({
        where: { username }
      });
    } catch (error) {
      throw new Error(`查找用户失败: ${error.message}`);
    }
  }

  // 根据用户名查找用户（别名方法，兼容authService调用）
  async findUserByUsername(username) {
    return await this.findByUsername(username);
  }

  // 根据ID查找用户
  async findById(id) {
    try {
      return await User.findByPk(id);
    } catch (error) {
      throw new Error(`查找用户失败: ${error.message}`);
    }
  }

  // 根据手机号查找用户
  async findByPhone(phone) {
    try {
      return await User.findOne({
        where: { phone }
      });
    } catch (error) {
      throw new Error(`查找用户失败: ${error.message}`);
    }
  }

  // 根据手机号查找用户（别名方法，兼容authService调用）
  async findUserByPhone(phone) {
    return await this.findByPhone(phone);
  }

  // 根据邮箱查找用户
  async findByEmail(email) {
    try {
      return await User.findOne({
        where: { email }
      });
    } catch (error) {
      throw new Error(`查找用户失败: ${error.message}`);
    }
  }

  // 根据邮箱查找用户（别名方法，兼容authService调用）
  async findUserByEmail(email) {
    return await this.findByEmail(email);
  }

  // 更新用户信息
  async updateUser(id, updateData) {
    try {
      const [affectedRows] = await User.update(updateData, {
        where: { id }
      });
      if (affectedRows === 0) {
        throw new Error('用户不存在');
      }
      return await this.findById(id);
    } catch (error) {
      throw new Error(`更新用户失败: ${error.message}`);
    }
  }

  // 更新最后登录时间
  async updateLastLogin(id) {
    try {
      return await User.update(
        { last_login_at: new Date() },
        { where: { id } }
      );
    } catch (error) {
      throw new Error(`更新登录时间失败: ${error.message}`);
    }
  }

  // 增加学习时长
  async addStudyTime(id, seconds) {
    try {
      const user = await this.findById(id);
      if (!user) {
        throw new Error('用户不存在');
      }
      return await User.update(
        { study_time: user.study_time + seconds },
        { where: { id } }
      );
    } catch (error) {
      throw new Error(`更新学习时长失败: ${error.message}`);
    }
  }

  // 增加积分
  async addPoints(id, points) {
    try {
      const user = await this.findById(id);
      if (!user) {
        throw new Error('用户不存在');
      }
      return await User.update(
        { points: user.points + points },
        { where: { id } }
      );
    } catch (error) {
      throw new Error(`更新积分失败: ${error.message}`);
    }
  }

  // 获取用户列表（分页）
  async getUserList(page = 1, limit = 10, filters = {}) {
    try {
      const offset = (page - 1) * limit;
      const where = {};

      // 构建查询条件
      if (filters.status) {
        where.status = filters.status;
      }
      if (filters.keyword) {
        where[Op.or] = [
          { username: { [Op.like]: `%${filters.keyword}%` } },
          { nickname: { [Op.like]: `%${filters.keyword}%` } },
          { phone: { [Op.like]: `%${filters.keyword}%` } }
        ];
      }

      const { count, rows } = await User.findAndCountAll({
        where,
        limit,
        offset,
        order: [['created_at', 'DESC']],
        attributes: { exclude: ['password'] }
      });

      return {
        total: count,
        list: rows,
        page,
        limit
      };
    } catch (error) {
      throw new Error(`获取用户列表失败: ${error.message}`);
    }
  }

  // 删除用户
  async deleteUser(id) {
    try {
      const affectedRows = await User.destroy({
        where: { id }
      });
      if (affectedRows === 0) {
        throw new Error('用户不存在');
      }
      return true;
    } catch (error) {
      throw new Error(`删除用户失败: ${error.message}`);
    }
  }

  // 检查用户名是否存在
  async isUsernameExists(username, excludeId = null) {
    try {
      const where = { username };
      if (excludeId) {
        where.id = { [Op.ne]: excludeId };
      }
      const user = await User.findOne({ where });
      return !!user;
    } catch (error) {
      throw new Error(`检查用户名失败: ${error.message}`);
    }
  }

  // 检查手机号是否存在
  async isPhoneExists(phone, excludeId = null) {
    try {
      const where = { phone };
      if (excludeId) {
        where.id = { [Op.ne]: excludeId };
      }
      const user = await User.findOne({ where });
      return !!user;
    } catch (error) {
      throw new Error(`检查手机号失败: ${error.message}`);
    }
  }

  // 检查邮箱是否存在
  async isEmailExists(email, excludeId = null) {
    try {
      const where = { email };
      if (excludeId) {
        where.id = { [Op.ne]: excludeId };
      }
      const user = await User.findOne({ where });
      return !!user;
    } catch (error) {
      throw new Error(`检查邮箱失败: ${error.message}`);
    }
  }
}

module.exports = new UserDao();
